package com.hbnrtech.sip.gb28181.handler;

import com.hbnrtech.sip.gb28181.deivce.DeviceRegistry;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.sip.*;
import javax.sip.address.SipURI;
import javax.sip.header.FromHeader;
import javax.sip.message.MessageFactory;
import javax.sip.message.Request;
import javax.sip.message.Response;
import java.text.ParseException;

/**
 * @author liuduo
 * @date 2025-04-21 15:56
 */
@Component
@Slf4j
public class SipKeepAliveHandler extends SipHandler {

    @Autowired
    private MessageFactory messageFactory;
    @Autowired
    private DeviceRegistry deviceRegistry;

    public void handleKeepAlive(RequestEvent requestEvent, ServerTransaction serverTransaction) throws InvalidArgumentException, SipException, ParseException {
        Request request = requestEvent.getRequest();
        // 判断设备是否已经注册
        FromHeader fromHeader = (FromHeader) request.getHeader(FromHeader.NAME);
        String deviceId = ((SipURI) fromHeader.getAddress().getURI()).getUser();
        DeviceRegistry.DeviceInfo device = deviceRegistry.getDevice(deviceId);
        if (device != null) {
            device.setExpiryTime(device.getExpiryTime().plusSeconds(3600)); // 更新过期时间
        }

        Response response = messageFactory.createResponse(Response.OK, request);
        serverTransaction.sendResponse(response);
    }
}
